<template>
  <el-dialog
    :title="title"
    :visible="dialogVisible"
    @close="btnCancel"
  >
    <!-- 表单区域 -->
    <el-form ref="roleForm" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
    </el-form>

    <!-- 下方按钮 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="4">
        <el-button @click="btnCancel">取 消</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addFn">确 定</el-button>
      </el-col>

    </el-row>

  </el-dialog>
</template>

<script>
import { addRole, getRoleList, updateRole } from '@/api/setting'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    page: {
      type: Object,
      required: true
    }

  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      const { rows } = await getRoleList({ page: 1, pagesize: this.page.total })
      rows.some(item => item.name === value) ? callback(new Error('该角色已添加')) : callback()
    }
    return {

      formData: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { trigger: 'blur', validator: checkNameRepeat // 自定义函数的形式校验
          }]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑角色' : '添加角色'
    }
  },
  methods: {
    // 添加角色
    addFn() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          if (this.formData.id) {
            // 编辑
            await updateRole(this.formData)
            this.$message.success('编辑角色成功')
          } else {
            // 添加
            // 后台数据更新
            await addRole(this.formData)
            // 提示用户
            this.$message.success('添加角色成功')
          }
          // 前端视图更新
          this.$emit('getRoleList')
          // 关闭弹层
          this.btnCancel()
        }
      })
    },
    // 取消
    btnCancel() {
      // 关闭弹层
      this.$emit('update:dialogVisible', false)
      // 清空验证
      this.$refs.roleForm.resetFields()
      // 删除id
      this.$delete(this.formData, 'id')
    },
    // 编辑
    async updateRole(data) {
      this.formData = data
    }

  }
}
</script>

<style>

</style>
